#!/usr/bin/env bash  
  
# 初始化关联数组来存储成功和失败次数  
declare -A successes  
declare -A failures  
  
# 函数：使用expect探测端口并更新计数器  
function probe_port {  
    local ip=$1  
    local port=$2  
    local key="${ip}:${port}"  
  
    # 使用expect来检查telnet的输出  
    /usr/bin/expect -c "  
    set timeout 5  
    spawn telnet $ip $port  
    expect {  
        timeout { exit 1 }  
        \"Connected to\" { exit 0 }  
        eof { exit 1 }  
    }  
    "  
  
    local result=$?  
    if [ $result -eq 0 ]; then  
        # 如果expect成功（即telnet输出了"Connected to"），则增加成功次数  
        ((successes["$key"]++))  
        echo "$key is open"  
    else  
        # 否则，增加失败次数  
        ((failures["$key"]++))  
        echo "$key is closed"  
    fi  
}  
  
# 探测IP和端口范围  
# 10.145.163.128-129:9001  
for ip in $(seq -w 128 129); do  
    probe_port "10.145.163.$ip" 9001  
done  
  
# 10.145.163.142-149:9201, 9199, 9601, 9599  
for ip in $(seq -w 142 149); do  
    for port in 9201 9199 9601 9599; do  
        probe_port "10.145.163.$ip" "$port"  
    done  
done  
  
# 10.145.171.146:9000-9004  
for port in $(seq 9000 9004); do  
    probe_port "10.145.171.146" "$port"  
done  
  
# 输出每个测试ip和端口的成功与失败次数  
echo "Summary of port probes:"  
for key in "${!successes[@]}"; do  
    echo "$key: Successes=${successes["$key"]}, Failures=${failures["$key"]:-0}"  
done  
  
# 如果需要，也可以输出失败的IP和端口  
echo "Failed probes:"  
for key in "${!failures[@]}"; do  
    echo "$key: Failures=${failures["$key"]}"  
done
